/**
 * Created by hldev on 17-1-10.
 */
import React, {Component} from 'react';
import {Button, notification, Form} from 'antd';
import BreadcrumbMain from "../breadcrumb/BreadcrumbMain"
import {articleTYPE, signTYPE} from '../../models/types';
import Utils from '../../common/Utils';
import {createFormItem} from "../commons/form";

export default class ArticleEditor extends Component {

    editor = null;

    componentDidMount() {
        this.editor = UE.getEditor('editor', {
            initialFrameWidth: '100%',initialFrameHeight: 320, autoHeightEnabled: true, toolbars: [[
                'fullscreen', 'source', '|', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                'directionalityltr', 'directionalityrtl', 'indent', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                'simpleupload', 'insertimage', 'attachment', '|',
                'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
                'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
                'print', 'preview', 'searchreplace', 'drafts', 'help'
            ]]
        });

        if (!this.isAdd()) {
            this.editor.addListener('ready', () => this.props.articleService.findById(this.props.params.id));
        }
    }

    componentWillUnmount() {
        if (this.editor) {
            this.editor.destroy();
        }
        this.props.articleService.clearArticle();
    }

    componentDidUpdate(prevProps, _) {
        if (prevProps.article.get(articleTYPE.ARTICLE) !== this.props.article.get(articleTYPE.ARTICLE)) {
            const article = Utils.getToObject(this.props.article, articleTYPE.ARTICLE);
            if (article.description) {
                this.refs.description.value = article.description;
            }
            if (article.title) {
                this.refs.title.value = article.title;
            }
            if (article.content) {
                this.editor.setContent(article.content);
            }
        }
    }

    isAdd = () => this.props.params.id === 'add';

    handleClick = () => {
        const content = this.editor.getContent();
        let category = null;
        if (!content) {
            notification.warn({message: '您未编辑正文'});
            return;
        }

        if (!this.refs.title.value) {
            notification.warn({message: '您未编辑标题'});
            return;
        }

        if (!this.props.form.getFieldValue("category")) {
            notification.warn({message: '您未选择类别'});
            return;
        }

        const user = Utils.getToObject(this.props.sign, signTYPE.SIGN_IN);

        const article = {
            ...Utils.getToObject(this.props.article, articleTYPE.ARTICLE),
            content: content,
            title: this.refs.title.value,
            description: this.refs.description.value,
            category: this.props.form.getFieldValue("category"),
            status: 1,
        };
        if (this.isAdd()) {
            this.props.articleService.create({...article, createBy: user.id});
            Utils.pushLink('/system/about/1');
        } else {
            this.props.articleService.update({...article, updateBy: user.id});
            const path = '/system/about/detail/' + this.props.params.id;
            Utils.pushLink(path);
        }
    };

    formControllers = () => {
        const formList = [{
            type: 'radio',
            name: 'category',
            options: {
                rules: [{required: true, message: '请选择文章类别！'}],
                initialValue: this.props.location.query.category
            },
            radioOptions: [
                {value: '1', label: '发展历史'},
                {value: '2', label: '教学内容'},
                {value: '3', label: '教师团队'},
                {value: '4', label: '教学成果'}
            ]
        },];

        return formList.map((config, key) => createFormItem(this.props.form.getFieldDecorator, config, key))
    };

    render() {
        // const category = articleCategoryList.find(obj => obj.id == this.props.params.categoryId);
        const article = Utils.getToObject(this.props.article, articleTYPE.ARTICLE);

        const breadcrumb = [
            {
                name: '首页',
                link: '/'
            }, {
                name: '关于课程',
                link: '/system/about/1',
            }, {
                name: this.isAdd() ? '创建文章' : '编辑文章',
            }
        ];


        return (
            <div>
                <BreadcrumbMain breadcrumb={breadcrumb}/>
                <div style={{margin: `0 100px`}}>
                    <div style={{margin: `10px 0`}}>
                        <p><strong>标题:</strong></p>
                        <input className="ant-input" ref="title"/>
                    </div>
                    <div style={{margin: `5px 0`}}>
                        <p><strong>摘要:</strong></p>
                        <textarea className="ant-input" ref="description"/>
                    </div>
                    <div>
                        <Form>
                            {this.formControllers()}
                        </Form>
                    </div>
                    <div>
                        <script id='editor' name="content" type="text/plain"></script>
                    </div>
                    <div>
                        <Button onClick={this.handleClick} style={{margin: '16px 10px'}}
                                type="primary">{this.isAdd() ? '创建' : '保存'}</Button>
                    </div>
                </div>
            </div>
        )
    }
}

ArticleEditor = Form.create()(ArticleEditor);